import React from 'react'
import { connect } from 'react-redux'
import CommonSelectDelete from 'src/pageP/common/common-select-delete'
import RefreshState from '../../../components/custom-flat-list/RefreshState'
import { cancelCollectionPost, myCenterNumbers, postCollectionList } from '../../../utils/RequestAPI'
import { CommonToast, DismissLoading, ShowLoading } from '../../../utils/ToastUtil'
import EmptyView from '../../../components/empty-view/index'
import { UPDATE_MY_CENTER_NUMBERS_ACTION } from '../../mine/mine-page/store/action'
import JobCell from '../../../components/job-cell/index'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateMyCenterNumbers (payload) {
    dispatch(UPDATE_MY_CENTER_NUMBERS_ACTION(payload))
  }
})

@connect(({ userinfo, CMineCenterStore, landmark }) => ({
  userinfoC: userinfo.C,
  role: userinfo.role,
  myCenterNumbers: CMineCenterStore.myCenterNumbers,
  landmark
}), mapDispatchToProps)
class CJobCollection extends CommonSelectDelete {
  constructor (props) {
    super(props)
    const { navigation: { state: { params: { userId: paramsUserId = '' } = {} } }, userinfoC: { userId }, role } = this.props
    this.state = {
      ...this.state,
      dataArr: [],
      titleNum: props.myCenterNumbers.postCollection || 0,
      paramsUserId: paramsUserId || '',
      isShowBtn: (!paramsUserId || paramsUserId == userId) && role === 'C'
    }
    this.titleText = '职位收藏'
    this.deleteText = '职位'
    this.page = 1
  }

  componentDidMount () {
    this.onHeaderRefresh()
  }

  generateItemChild (itemParams) {
    const { item } = itemParams
    const jobItem = {
      ...item,
      basicInfoModel: {
        name: item.name,
        settlementMethod: item.settlementMethod,
        salary: item.salary,
        category: item.category,
        practiceLabel: item.practiceLabel,
        type: item.type
      }
    }
    return (
      <JobCell item={jobItem} landmark={this.props.landmark} isCollection={true}/>
    )
  }

  childItemClick ({ item }) {
    const blockCallback = () => {
      console.log('blockCallback')
      const { dataArr } = this.state
      this.setState({
        dataArr: dataArr.filter(e => e.id !== item.id)
      })
    }
    this.props.navigation.navigate('CJobdetail', {
      id: item.postId,
      blockCallback
    })
  }

  listEmptyComponent () {
    return <EmptyView
      emptyImg={require('src/imgC/userinfo/job-collection-null.png')}
      firstTip={'无收藏职位'}
      secondTip={'快去寻找更多职位吧～'}/>
  }

  onHeaderRefresh () {
    this.page = 1
    this._myCenterNumber()
    this._postCollectionList(true).then((datas) => {
      this.setState(() => ({
        dataArr: datas
      }), () => {
        this._refreshState(datas)
      })
    })
  }

  _myCenterNumber = () => {
    const { userinfoC: { userId } } = this.props
    const { paramsUserId } = this.state
    myCenterNumbers({
      params: {
        type: 'C',
        userId: paramsUserId || userId
      },
      headers: {
        userId: paramsUserId || userId
      }
    }).then(res => {
      this._setPostCollectionState(res.data.postCollection)
    })
  }

  _setPostCollectionState = (titleNum) => {
    this.setState({
      titleNum
    })
  }

  onFooterRefresh () {
    ++this.page
    this._postCollectionList().then((datas) => {
      this.setState(() => ({
        dataArr: this.state.dataArr.concat(datas)
      }), () => {
        this._refreshState(datas)
      })
    })
  }

  _postCollectionList = (showLoading) => {
    showLoading && ShowLoading()
    const { userinfoC } = this.props
    const { paramsUserId } = this.state
    return new Promise((resolve) => {
      postCollectionList({
        params: {
          page: this.page,
          limit: 10,
          userId: paramsUserId || userinfoC.userId
        },
        headers: {
          userId: paramsUserId || userinfoC.userId
        }
      }).then((data) => {
        showLoading && DismissLoading()
        console.info(data)
        resolve(data.data)
      }).catch(() => {
        showLoading && DismissLoading()
      })
    })
  }

  _refreshState = (datas) => {
    if (datas.length > 9) {
      this.flatListRef.endRefreshing(RefreshState.CanLoadMore)
    } else {
      this.flatListRef.endRefreshing(RefreshState.NoMoreData)
    }
  }

  confirmDelete () {
    ShowLoading()
    const { dataArr, checkedIndexes } = this.state
    const idArr = dataArr.reduce((idArr, currentValue, index) => {
      return checkedIndexes.includes(index) ? idArr.concat(currentValue.id) : idArr
    }, [])
    cancelCollectionPost({
      params: {
        ids: idArr.join(',')
      }
    }).then((data) => {
      DismissLoading()
      CommonToast(`${checkedIndexes.length}条职位收藏删除成功`)
      this._myCenterNumber()
      const remainData = dataArr.filter((item, index) => {
        return !checkedIndexes.includes(index)
      })
      if (remainData.length <= 0) {
        this.flatListRef.endRefreshing(RefreshState.Idle)
      }
      this.setState({
        checkedIndexes: [],
        dataArr: remainData
      })
    }).catch(() => {
      DismissLoading()
    })
  }
}

export default CJobCollection
